/**
 * 静态模拟数据
 * 不再使用Mock.js动态生成数据，而是直接提供固定数据
 */

// 用户总览数据
const userOverviewData = {
  success: true,
  data: {
    offlineNum: 35,
    lockNum: 8,
    totalNum: 218,
    onlineNum: 175 // 218 - 35 - 8
  }
};

// 设备总览数据
const deviceOverviewData = {
  success: true,
  data: {
    alarmNum: 568,
    offlineNum: 27,
    totalNum: 698,
    onlineNum: 671 // 698 - 27
  }
};

// 设备提醒列表数据
const deviceAlertData = {
  success: true,
  data: {
    list: [
      {
        provinceName: "河北省",
        cityName: "唐山市",
        countyName: "路南区",
        createTime: "2025-05-15 08:38:33",
        deviceId: "6c512d754bbcd6d7cd86abce0e0cac58",
        gatewayno: 10001,
        onlineState: 1
      },
      {
        provinceName: "河北省",
        cityName: "唐山市",
        countyName: "路北区",
        createTime: "2025-05-15 09:12:45",
        deviceId: "7d623e865ccde7e8de97bcdf1f1dbd69",
        gatewayno: 10002,
        onlineState: 0
      },
      {
        provinceName: "河北省",
        cityName: "唐山市",
        countyName: "开平区",
        createTime: "2025-05-15 10:25:18",
        deviceId: "8e734f976ddef8f9ef08cde020ece70",
        gatewayno: 10003,
        onlineState: 1
      },
      {
        provinceName: "河北省",
        cityName: "唐山市",
        countyName: "丰南区",
        createTime: "2025-05-15 11:37:22",
        deviceId: "9f845g087eefg9g0fg19def131fdf81",
        gatewayno: 10004,
        onlineState: 1
      },
      {
        provinceName: "河北省",
        cityName: "唐山市",
        countyName: "丰润区",
        createTime: "2025-05-15 12:48:56",
        deviceId: "0g956h198ffgh0h1gh20efg242geg92",
        gatewayno: 10005,
        onlineState: 0
      }
    ]
  }
};

// 中国地图数据
const chinaMapData = {
  success: true,
  data: {
    dataList: [
      { name: "河北省", value: 856 },
      { name: "山东省", value: 678 },
      { name: "辽宁省", value: 543 },
      { name: "黑龙江省", value: 432 },
      { name: "吉林省", value: 321 },
      { name: "内蒙古", value: 298 },
      { name: "山西省", value: 276 },
      { name: "陕西省", value: 245 }
    ],
    regionCode: 'china'
  }
};

// 河北省地图数据
const hebeiMapData = {
  success: true,
  data: {
    dataList: [
      { name: "唐山市", value: 325 },
      { name: "石家庄市", value: 287 },
      { name: "保定市", value: 243 },
      { name: "邯郸市", value: 198 },
      { name: "秦皇岛市", value: 176 },
      { name: "廊坊市", value: 165 },
      { name: "邢台市", value: 154 },
      { name: "沧州市", value: 143 },
      { name: "衡水市", value: 132 },
      { name: "张家口市", value: 121 },
      { name: "承德市", value: 110 }
    ],
    regionCode: '130000'
  }
};

// 报警次数数据
const alarmNumData = {
  success: true,
  data: {
    dateList: ['2025-05', '2025-06', '2025-07', '2025-08', '2025-09', "2025-10"],
    numList: [325, 412, 287, 356, 298, 432],
    numList2: [187, 243, 176, 198, 165, 254]
  }
};

// 报警排名数据
const alarmRankingData = {
  success: true,
  data: [
    { name: "路南区", value: 108 },
    { name: "路北区", value: 95 },
    { name: "开平区", value: 82 },
    { name: "丰南区", value: 75 },
    { name: "丰润区", value: 68 },
    { name: "古冶区", value: 55 },
    { name: "曹妃甸区", value: 42 },
    { name: "滦南县", value: 35 }
  ]
};

// 安装计划数据
const installationPlanData = {
  success: true,
  data: {
    category: ["唐山市", "石家庄市", "保定市", "邯郸市", "秦皇岛市", "廊坊市", "邢台市", "沧州市", "衡水市", "张家口市", "承德市"],
    barData: [65, 58, 52, 48, 45, 42, 38, 35, 32, 28, 25],
    lineData: [85, 75, 68, 62, 58, 54, 49, 45, 41, 36, 32],
    rateData: [76, 77, 76, 77, 78, 78, 78, 78, 78, 78, 78]
  }
};

// 实时预警数据
const realTimeAlertData = {
  success: true,
  data: {
    list: [
      {
        alertdetail: "水位超过警戒线",
        alertname: "水浸告警",
        alertvalue: 78.5,
        createtime: "2025-05-16 08:38:33",
        deviceid: null,
        gatewayno: 10001,
        phase: "A1",
        sbInfo: "路南区变电站设备异常",
        terminalno: 101,
        provinceName: "河北省",
        cityName: "唐山市",
        countyName: "路南区"
      },
      {
        alertdetail: "温度过高",
        alertname: "温度告警",
        alertvalue: 87.2,
        createtime: "2025-05-16 08:42:15",
        deviceid: null,
        gatewayno: 10002,
        phase: "B2",
        sbInfo: "路北区变电站设备异常",
        terminalno: 102,
        provinceName: "河北省",
        cityName: "唐山市",
        countyName: "路北区"
      }
    ]
  }
};

/**
 * 模拟接口响应
 * @param {String} url 请求URL
 * @param {String} matchedApi 匹配到的API路径
 * @returns {Object} 响应数据
 */
function mockResponse(url, matchedApi) {
  // 解析URL参数
  const params = getUrlParams(url);
  
  // console.log('mockResponse处理URL:', url, '匹配API:', matchedApi);
  
  // 生成随机因子，模拟数据变化
  const randomFactor = Math.random() * 0.2 + 0.9; // 0.9-1.1的随机因子
  
  // 优先使用matchedApi进行匹配
  if (matchedApi) {
    // console.log('使用匹配到的API:', matchedApi);
    
    // 用户总览
    if (matchedApi === 'countUserNum' || matchedApi.includes('countUserNum')) {
      // console.log('返回用户总览数据');
      return {
        success: true,
        code: 200,
        msg: 'success',
        data: {
          lockNum: Math.floor(8 * randomFactor),
          onlineNum: Math.floor(175 * randomFactor),
          offlineNum: Math.floor(35 * randomFactor),
          totalNum: Math.floor(218 * randomFactor)
        }
      };
    } else if (matchedApi === 'countDeviceNum' || matchedApi.includes('countDeviceNum')) {
      // console.log('返回设备总览数据');
      return {
        success: true,
        code: 200,
        msg: 'success',
        data: {
          alarmNum: Math.floor(568 * randomFactor),
          offlineNum: Math.floor(27 * randomFactor),
          totalNum: Math.floor(698 * randomFactor),
          onlineNum: Math.floor(671 * randomFactor)
        }
      };
    } else if (matchedApi === 'sbtx' || matchedApi.includes('sbtx')) {
      // console.log('返回设备提醒数据');
      // 添加随机因子使数据有变化
      const randomizedData = JSON.parse(JSON.stringify(deviceAlertData));
      randomizedData.data.list = randomizedData.data.list.map(item => {
        // 随机调整创建时间
        const date = new Date(item.createTime);
        date.setMinutes(date.getMinutes() + Math.floor(Math.random() * 30));
        item.createTime = date.toISOString().replace('T', ' ').substring(0, 19);
        return item;
      });
      return randomizedData;
    } else if (matchedApi === 'centermap' || matchedApi.includes('centermap')) {
      // 根据regionCode参数返回不同的地图数据
      if (params.regionCode && params.regionCode === '130000') {
        // console.log('返回河北省地图数据');
        // 深拷贝地图数据以避免修改原始数据
        const mapData = JSON.parse(JSON.stringify(hebeiMapData));
        
        // 为每个城市添加随机数据变化
        mapData.data.dataList.forEach(item => {
          if (item.value) {
            // 在原值基础上增加或减少最多10%
            const changeFactor = 0.9 + Math.random() * 0.2; // 0.9-1.1的随机因子
            item.value = Math.floor(item.value * changeFactor);
          }
        });
        
        return mapData;
      } else {
        // console.log('返回中国地图数据');
        // 深拷贝地图数据以避免修改原始数据
        const mapData = JSON.parse(JSON.stringify(chinaMapData));
        
        // 为每个省份添加随机数据变化
        mapData.data.dataList.forEach(item => {
          if (item.value) {
            // 在原值基础上增加或减少最多10%
            const changeFactor = 0.9 + Math.random() * 0.2; // 0.9-1.1的随机因子
            item.value = Math.floor(item.value * changeFactor);
          }
        });
        
        return mapData;
      }
    } else if (matchedApi === 'alarmNum' || matchedApi.includes('alarmNum')) {
      // console.log('返回报警次数数据');
      // 深拷贝报警次数数据以避免修改原始数据
      const randomizedData = JSON.parse(JSON.stringify(alarmNumData));
      // 为数据添加随机变化
      randomizedData.data.numList = randomizedData.data.numList.map(num => Math.floor(num * randomFactor));
      randomizedData.data.numList2 = randomizedData.data.numList2.map(num => Math.floor(num * randomFactor));
      return randomizedData;
    } else if (matchedApi === 'ssyj' || matchedApi.includes('ssyj')) {
      // console.log('返回实时预警数据');
      // 深拷贝实时预警数据以避免修改原始数据
      const randomizedData = JSON.parse(JSON.stringify(realTimeAlertData));
      
      // 为数据添加随机变化
      randomizedData.data.list = randomizedData.data.list.map(item => {
        // 随机调整创建时间
        const date = new Date(item.createtime);
        date.setMinutes(date.getMinutes() + Math.floor(Math.random() * 30));
        item.createtime = date.toISOString().replace('T', ' ').substring(0, 19);
        
        // 随机调整告警值
        if (item.alertvalue) {
          const changeFactor = 0.95 + Math.random() * 0.1; // 0.95-1.05的随机因子
          item.alertvalue = parseFloat((item.alertvalue * changeFactor).toFixed(1));
        }
        
        return item;
      });
      
      return randomizedData;
    } else if (matchedApi === 'installationPlan' || matchedApi.includes('installationPlan')) {
      // console.log('返回安装计划数据');
      // 深拷贝安装计划数据以避免修改原始数据
      const randomizedData = JSON.parse(JSON.stringify(installationPlanData));
      // 为数据添加随机变化
      randomizedData.data.barData = randomizedData.data.barData.map(num => Math.floor(num * randomFactor));
      randomizedData.data.lineData = randomizedData.data.lineData.map(num => Math.floor(num * randomFactor));
      randomizedData.data.rateData = randomizedData.data.rateData.map(num => Math.floor(num * (0.95 + Math.random() * 0.1)));
      return randomizedData;
    } else if (matchedApi === 'ranking' || matchedApi.includes('ranking')) {
      // console.log('返回报警排名数据');
      // 深拷贝报警排名数据以避免修改原始数据
      const randomizedData = JSON.parse(JSON.stringify(alarmRankingData));
      // 为数据添加随机变化
      randomizedData.data = randomizedData.data.map(item => {
        if (item.value) {
          const changeFactor = 0.9 + Math.random() * 0.2; // 0.9-1.1的随机因子
          item.value = Math.floor(item.value * changeFactor);
        }
        return item;
      });
      return randomizedData;
    }
  }
  
  // 如果matchedApi没有匹配到，则使用URL进行匹配
  if (url.includes('countUserNum')) {
    // console.log('返回用户总览数据');
    return userOverviewData;
  } else if (url.includes('countDeviceNum')) {
    // console.log('返回设备总览数据');
    return deviceOverviewData;
  } else if (url.includes('sbtx')) {
    // console.log('返回设备提醒数据');
    return deviceAlertData;
  } else if (url.includes('centermap')) {
    // 根据regionCode参数返回不同的地图数据
    if (params.regionCode && params.regionCode === '130000') {
      // console.log('返回河北省地图数据');
      return hebeiMapData;
    } else {
      // console.log('返回中国地图数据');
      return chinaMapData;
    }
  } else if (url.includes('alarmNum')) {
    // console.log('返回报警次数数据');
    return alarmNumData;
  } else if (url.includes('ssyj')) {
    // console.log('返回实时预警数据');
    return realTimeAlertData;
  } else if (url.includes('installationPlan')) {
    // console.log('返回安装计划数据');
    return installationPlanData;
  } else if (url.includes('ranking')) {
    // console.log('返回报警排名数据');
    return alarmRankingData;
  }
  
  // 默认返回空数据
  return { success: false, message: '未找到对应接口' };
}

/**
 * 获取URL参数
 * @param {String} url URL字符串
 * @return {Object} 参数对象
 */
function getUrlParams(url) {
  const params = {};
  if (url.includes('?')) {
    const queryString = url.split('?')[1];
    const paramPairs = queryString.split('&');
    for (const pair of paramPairs) {
      const [key, value] = pair.split('=');
      params[key] = value;
    }
  }
  return params;
}

// 拦截XMLHttpRequest
(function() {
  // 防止重复初始化
  if (window.__mockDataInitialized) {
    // console.log('Mock数据已经初始化，跳过');
    return;
  }
  
  const originalXHR = window.XMLHttpRequest;
  
  // 调试信息
  // console.log('开始拦截XMLHttpRequest请求');
  
  function MockXHR() {
    const xhr = new originalXHR();
    
    // 重写open方法
    const originalOpen = xhr.open;
    xhr.open = function(method, url, ...args) {
      this.mockUrl = url;
      // console.log('拦截到XHR请求:', method, url);
      return originalOpen.apply(this, [method, url, ...args]);
    };
    
    // 重写send方法
    const originalSend = xhr.send;
    xhr.send = function(...args) {
      const mockUrl = this.mockUrl;
      
      // 检查是否需要拦截 - 支持带baseUrl和不带baseUrl的情况
      const apiEndpoints = [
        'countUserNum', 'countDeviceNum', 'sbtx', 'centermap',
        'alarmNum', 'ssyj', 'installationPlan', 'ranking'
      ];
      
      // 检查是否匹配任何API路径
      let shouldMock = false;
      let matchedApi = '';
      
      // 检查是否匹配完整URL路径
      const baseUrlPattern = 'http://localhost:8888/bigscreen/';
      
      if (mockUrl.startsWith(baseUrlPattern)) {
        shouldMock = true;
        matchedApi = mockUrl.substring(baseUrlPattern.length).split('?')[0];
        // console.log('匹配到完整URL路径:', mockUrl, '提取API:', matchedApi);
      }
      // 检查是否匹配相对路径 /bigscreen/
      else if (mockUrl.includes('/bigscreen/')) {
        shouldMock = true;
        matchedApi = mockUrl.split('/bigscreen/')[1].split('?')[0];
        // console.log('匹配到相对API路径:', matchedApi);
      } 
      // 检查是否直接匹配API名称
      else {
        shouldMock = apiEndpoints.some(api => {
          const match = mockUrl.includes(api);
          if (match) matchedApi = api;
          return match;
        });
        if (shouldMock) {
          // console.log('直接匹配到API名称:', matchedApi);
        }
      }
      
      // 保存匹配到的API路径，用于后续处理
      this.matchedApi = matchedApi;
      
      // 调试信息
      // console.log('请求URL:', mockUrl, '是否拦截:', shouldMock);
      
      if (shouldMock) {
        // 模拟异步响应
        setTimeout(() => {
          try {
            // 使用保存的matchedApi和完整URL来获取响应数据
            const response = mockResponse(mockUrl, this.matchedApi);
            
            if (response) {
              Object.defineProperty(this, 'response', { value: response });
              Object.defineProperty(this, 'responseText', { value: JSON.stringify(response) });
              Object.defineProperty(this, 'status', { value: 200 });
              Object.defineProperty(this, 'readyState', { value: 4 });
              
              // console.log('模拟响应数据:', response);
            } else {
              // 没有匹配的模拟数据，返回404
              // console.warn(`没有找到匹配的模拟数据: ${this.matchedApi || mockUrl}`);
              Object.defineProperty(this, 'response', { value: {success: false, code: 404, msg: '没有找到匹配的模拟数据'} });
              Object.defineProperty(this, 'responseText', { value: JSON.stringify({success: false, code: 404, msg: '没有找到匹配的模拟数据'}) });
              Object.defineProperty(this, 'status', { value: 404 });
              Object.defineProperty(this, 'readyState', { value: 4 });
            }
          } catch (error) {
            // 处理错误
            // console.error('模拟响应出错:', error);
            Object.defineProperty(this, 'response', { value: {success: false, code: 500, msg: '模拟响应出错: ' + error.message} });
            Object.defineProperty(this, 'responseText', { value: JSON.stringify({success: false, code: 500, msg: '模拟响应出错: ' + error.message}) });
            Object.defineProperty(this, 'status', { value: 500 });
            Object.defineProperty(this, 'readyState', { value: 4 });
          }
          
          // 触发事件
          if (this.onreadystatechange) {
            this.onreadystatechange();
          }
          if (this.onload) {
            this.onload();
          }
        }, Math.random() * 300 + 100); // 随机延迟100-400ms
        
        return;
      }
      
      // 不需要拦截的请求正常发送
      return originalSend.apply(this, args);
    };
    
    return xhr;
  }
  
  // 替换原生XMLHttpRequest
  window.XMLHttpRequest = MockXHR;
  
  // 设置初始化标志
  window.__mockDataInitialized = true;
  
  console.log('静态模拟数据已加载，XMLHttpRequest已被拦截');
})();

// console.log('静态模拟数据模块执行完毕');

// 导出所有模拟数据，以便直接在组件中使用
export {userOverviewData, deviceOverviewData, deviceAlertData, chinaMapData, hebeiMapData, alarmNumData, alarmRankingData, installationPlanData, realTimeAlertData};